/**
 * @description 通过puppeteer来获取免费歌曲下载
 * 定义需要查询歌曲的列表
 * 打开浏览器并跳转到网站
 * 循环歌曲列表：
 * 找到查询歌曲输入框
 * 通过page.type输入歌曲
 * 点击查询
 * 获取歌曲下载地址
 * 将歌曲地址保存
 * 递归下一
 *
 *
 */
const puppeteer = require("puppeteer");

const url = "https://music.txqq.pro/";

const getElementPosition = async (element) => {
  let box = await element.boundingBox();
  console.log("box: ", box);
  const x = box.x + box.width / 2;
  console.log("x : ", x);
  const y = box.y + box.height / 2;
  console.log("y: ", y);
  return { x, y };
};

const getBrowserNewTab = (browser)=>{
  return new Promise(res => 
    browser.once('targetcreated', 
      target => res(target.page())
    )
  )
}

const startDownload = async () => {
  //打开浏览器
  const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: null,
    args: ["--start-fullscreen"],
  });
  browser.on("disconnected", () => {
    console.log("disconnected ------------");
  });
  //打开页面
  const page = await browser.newPage();
  await page.setViewport({
    width: 2280,
    height: 2200,
  });
  await page.goto(url);
  await page.waitForTimeout(2000);

  // 输入歌曲
  const inputEle = await page.$("#j-input");
  console.log("inputEle: ", inputEle);
  page.type("#j-input", "冬天");
  await page.waitForTimeout(2000);

  // 选择平台
  const platformEle = await page.$(".am-radio-inline");
  console.log("platformEle: ", platformEle);
  const platformPos = await getElementPosition(platformEle);
  page.mouse.click(platformPos.x, platformPos.y);
  // 查找歌曲
  const element = await page.$("#j-submit");
  const { x, y } = await getElementPosition(element);
  page.mouse.click(x, y);
  await page.waitForTimeout(2000);

  page.click("#j-src-btn")
  const downloadPage = await getBrowserNewTab(browser);
  await page.waitForTimeout(1000);
  // page.goBack();
  console.log('========= download url =====',downloadPage.url());
  downloadPage.close();

  //close browser
  // await browser.close();
};

startDownload();
